import { Controller, Get, Query, Res } from '@nestjs/common';
import express from 'express';
import fetch from 'node-fetch';
import { Public } from '../shared/decorators/public.decorator';

const CLIENT_KEY = 'sbawczl4qpz9j8q1u0';
const CLIENT_SECRET = 'vIl5HCzGzcTMPV8yvywMdnJHE8Gl9e0V';
const REDIRECT_URI =
  'https://272931014b1c.ngrok-free.app/blog/tLogin/auth/tiktok/callback'; //该地址是 tiktok控制台配置的重定向地址需要保持一致

interface TikTokTokenResponse {
  access_token: string;
  expires_in: number;
  refresh_token: string;
  refresh_expires_in: number;
  open_id: string;
  scope: string;
  token_type: string;
}

@Public()
@Controller('tLogin/auth/tiktok')
export class TikTokController {
  // login可以放在前端去跳转，重定向页面（“授权登录确认页面，tiktok提供的”）
  @Get('login')
  login(@Res() res: express.Response) {
    const url =
      `https://www.tiktok.com/v2/auth/authorize` +
      `?client_key=${CLIENT_KEY}` +
      `&scope=user.info.basic` +
      `&response_type=code` +
      `&redirect_uri=${encodeURIComponent(REDIRECT_URI)}`;
    res.redirect(url);
  }

  @Get('callback')
  async callback(@Query('code') code: string, @Res() res: express.Response) {
    try {
      const tokenRes = await fetch(
        'https://open.tiktokapis.com/v2/oauth/token/',
        {
          method: 'POST',
          headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
          body: new URLSearchParams({
            client_key: CLIENT_KEY,
            client_secret: CLIENT_SECRET,
            code,
            grant_type: 'authorization_code',
            redirect_uri: REDIRECT_URI,
          }),
        },
      );

      const tokenData = (await tokenRes.json()) as TikTokTokenResponse;
      // 拿到后可以重定向前端页面，tokenData就是登陆后的信息了
      res.json(tokenData);
    } catch (err: unknown) {
      if (err instanceof Error) {
        res.status(500).json({ error: err.message });
      } else {
        res.status(500).json({ error: String(err) });
      }
    }
  }
}
